import axios from 'axios'
import {
	Api_url,
	IsDemo
} from './config'
import {
	Message
} from 'element-ui'



const check_demo = () => {
	Message({
		message: "演示版",
		type: 'error',
		duration: 5 * 1000
	})
}

//创建axios实例
var service = axios.create({
	baseURL: Api_url,
	timeout: 60000
})

//添加响应拦截器
service.interceptors.response.use(function(response) {
	const status = response.status
	const res = response.data 
	
	if (status != 200) {
		Message({
			message: "请求错误", //后端返回错误类型
			type: 'error',
			duration: 5 * 1000
		})
		return res
	} else {
		return res
	}
}, function(err) {
	console.log('错误消息下');
	console.dir(err)
	console.log('错误消息上');
	let status = err.response.request.status
	switch(status)
	{
		case 404:
		Message({
			showClose: true,
			message: '数据错误',
			type: 'error'
		});
		break
		default:
			Message({
				showClose: true,
				message: '未知错误',
				type: 'error'
			});
		break
		
		
	}
	return Promise.reject(err)
})

export default {
	service,
	//get请求
	get(url, data) {
		return service({
			url: url,
			method: 'get',
			data
		})
	},
	//del请求
	delete(url) {
		return service({
			url: url,
			method: 'delete'
		})
	},
	//便于切换演示版
	get_show(url, data) {
		if (IsDemo) {
			check_demo()
			return;
		}
		return service({
			url: url,
			method: 'get',
			data
		})
	},
	//post请求
	post(url, data) {
		return service({
			url: url,
			method: 'post',
			data
		})
	},
	Del(url, data) {
		if (IsDemo) {
			check_demo()
			return;
		}
		return service({
			url: url,
			method: 'delete',
			data
		})
	},
	//便于切换演示版
	post_show(url, data) {
		if (IsDemo) {
			check_demo()
			return;
		}
		return service({
			url: url,
			method: 'post',
			data
		})
	},
	//put请求
	//便于切换演示版
	put_show(url, data) {
		if (IsDemo) {
			check_demo()
			return;
		}
		return service({
			url: url,
			method: 'put',
			data
		})
	}
}
